package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Category;
import org.csu.mypetstore.service.AdminCatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.lang.model.element.Name;
import java.io.File;

@Controller
@RequestMapping("/catalog")
public class AdminCategoryController {

    @Autowired
    private AdminCatalogService adminCatalogService;

    @GetMapping("/list")
    public String listCategories(Model model) {
        model.addAttribute("categories", adminCatalogService.listCategories());
        return "admin/categoryList";
    }

    @GetMapping("/AdminAddCategory")
    public String editCategory(@RequestParam(required = false) String categoryId, Model model) {
        if (categoryId != null) {
            Category category = adminCatalogService.getCategory(categoryId);
            model.addAttribute("category", category);
        } else {
            model.addAttribute("category", new Category());
        }
        return "admin/editCategory";
    }

    @PostMapping("/save")
    public String saveCategory(@ModelAttribute Category category,
                               @RequestParam("name") String name){
        if (category.getCategoryId() == null || category.getCategoryId().isEmpty()) {
            //没有categordid 则新建category
            String categoryid=name.toUpperCase();
            category.setCategoryId(categoryid);
            adminCatalogService.addCategory(category);
        } else {
            //在原有的category上进行更改
            adminCatalogService.updateCategory(category);
        }
        return "redirect:/catalog/list";
    }

    @GetMapping("/delete")
    public String deleteCategory(@RequestParam String categoryId) {
        adminCatalogService.deleteCategory(categoryId);
        return "redirect:list";
    }

}
